// 定义评论相关的接口
const express = require('express');
const router = express.Router();
const Joi = require('joi');
const Response = require('../utils/Response.js');
// 引入mysql连接池
const pool = require('../utils/db.js');

/**
 * 通过hmid查评论信息
 * @params : id
 */
router.get('/discuss/query', (req, resp) => {
  let { id } = req.query;
  // 表单验证
  let schema = Joi.object({
    id: Joi.string().required(),
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return;
  }
  // 执行查询业务
  let sql = `select di.*,dm.* from discuss_img di left join discuss_message dm on di.d_id=dm.did left join hotel_message hm on hm.hmid=dm.hm_id where hmid=?`;
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result && result.length == 0) {
      resp.send(Response.ok(null));
    } else {
      resp.send(Response.ok(result));
    }
  });
});
/**
 * 添加评论
 * params {}
 */
router.post('/discuss/add', (req, resp) => {
  // post请求参数在req.body
  let { uname, phone, detail, o_id, hm_id, pic1, pic2, pic3 } = req.body;
  //   表单验证
  let schema = Joi.object({
    uname: Joi.string().required(),
    phone: Joi.string().required(),
    detail: Joi.string().required(),
    o_id: Joi.number().required(),
    hm_id: Joi.number().required(),
    pic1: Joi.string().min(0).allow('').allow(null),
    pic2: Joi.string().min(0).allow('').allow(null),
    pic3: Joi.string().min(0).allow('').allow(null),
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return;
    // 验证错误，结束
  }
  // 验证通过，添加
  let sql = `insert into discuss_message(uname,phone,detail,o_id,hm_id) values (?,?,?,?,?)`;
  pool.query(sql, [uname, phone, detail, o_id, hm_id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    // 获取当前评论id，新增discuss_img表
    let insertId = result.insertId;
    let sql2 = 'insert into discuss_img(d_id,pic1,pic2,pic3) values (?,?,?,?)';
    pool.query(sql2, [insertId, pic1, pic2, pic3], (error2, result2) => {
      if (error2) {
        resp.send(Response.error(500, error2));
        throw error2;
      }
      resp.send(Response.ok());
    });
  });
});

// 将router对象导出
module.exports = router;
